<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { ref, watch, onBeforeUnmount, shallowRef } from "vue";
import { message } from "@/utils/message";
import { FormInstance } from "element-plus";
import { addOrUpdateAppModule } from "@/api/syschat";
import { uploadModule } from "@/api/sysupload";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => {
      return {};
    }
  },
  bmdata: {
    type: Object,
    default: () => {
      return [];
    }
  }
});

const ruleFormRef = ref<FormInstance>();

const formVisible = ref(false);
const formData = ref(props.data);
const fileList = ref([]);
const mdFileList = ref([]);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      addOrUpdateAppModule(formData.value)
        .then(res => {
          if (res.success) {
            message("提交成功", { type: "success" });
            formVisible.value = false;
            resetForm(formEl);
            emit("add-up-search"); //用emit来进行事件通知传递
          } else {
            message("提交失败:" + res.errMsg, { type: "error" });
          }
        })
        .catch(error => {
          message("提交失败:" + JSON.stringify(error), { type: "error" });
        });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const closeDialog = () => {
  formVisible.value = false;
  resetForm(ruleFormRef.value);
};

const emit = defineEmits(["update:visible", "add-up-search"]);
watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);

watch(
  () => props.data,
  val => {
    formData.value = val;
    if (formData.value.image) {
      const filename = formData.value.image.substring(
        formData.value.image.lastIndexOf("/") + 1
      );
      fileList.value = [{ name: filename, url: formData.value.image }];
    } else {
      fileList.value = [];
    }
    if (formData.value.mdurl) {
      const filename = formData.value.mdurl.substring(
        formData.value.mdurl.lastIndexOf("/") + 1
      );
      mdFileList.value = [{ name: filename, url: formData.value.mdurl }];
    } else {
      mdFileList.value = [];
    }
  }
);

const rules = {
  name: [{ required: true, message: "请输入插件名称", trigger: "blur" }],
  // manageid: [{ required: true, message: "请选择小区", trigger: "blur" }],
  // type: [{ required: true, message: "请选择类型", trigger: "blur" }],
  // des: [{ required: true, message: "请输入描述简介", trigger: "blur" }],
  // content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
  // zt: [{ required: true, message: "请选择状态", trigger: "blur" }],
  // noticetime: [{ required: true, message: "请输入发布时间", trigger: "blur" }],
  orderby: [{ required: true, message: "请输入排序顺序", trigger: "blur" }]
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const beforeUpload = async file => {
  const form = new FormData();
  form.append("file", file);
  uploadModule(form)
    .then(res => {
      if (res.errno == 0) {
        message("上传成功", { type: "success" });
        fileList.value = [{ name: res.data.alt, url: res.data.url }];
        formData.value.image = res.data.url;
        return false;
      } else {
        message("上传失败:" + res.message, { type: "error" });
        return false;
      }
    })
    .catch(error => {
      message("上传失败:" + JSON.stringify(error), { type: "error" });
      return false;
    });
};

const beforeRemove = () => {
  fileList.value = [];
  formData.value.image = "";
  return false;
};

const beforeMdUpload = async file => {
  const form = new FormData();
  form.append("file", file);
  uploadModule(form)
    .then(res => {
      if (res.errno == 0) {
        message("上传成功", { type: "success" });
        mdFileList.value = [{ name: res.data.alt, url: res.data.url }];
        formData.value.mdurl = res.data.url;
        return false;
      } else {
        message("上传失败:" + res.message, { type: "error" });
        return false;
      }
    })
    .catch(error => {
      message("上传失败:" + JSON.stringify(error), { type: "error" });
      return false;
    });
};

const beforeMdRemove = () => {
  mdFileList.value = [];
  formData.value.mdurl = "";
  return false;
};
</script>

<template>
  <el-dialog
    v-model="formVisible"
    title="编辑插件"
    :width="680"
    draggable
    :before-close="closeDialog"
  >
    <!-- 表单内容 -->
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="平台" prop="platform">
        <el-radio-group v-model="formData.platform">
          <el-radio label="1">用友</el-radio>
          <el-radio label="2">uni-app</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input
          v-model="formData.name"
          :style="{ width: '480px' }"
          placeholder="请输入名称"
        />
      </el-form-item>

      <el-form-item label="标签" prop="tag">
        <el-input
          v-model="formData.tag"
          :style="{ width: '480px' }"
          placeholder="请输入名称"
        />
      </el-form-item>

      <el-form-item label="封面" prop="image">
        <img
          v-if="formData.image"
          :src="formData.image"
          style="width: 125px; height: 89px"
        />
        <el-upload
          action="upload"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          multiple
          :auto-upload="true"
          :file-list="fileList"
          :limit="1"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述" prop="content">
        <el-input
          type="textarea"
          v-model="formData.content"
          :style="{ width: '480px' }"
          placeholder="请输入描述"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
          v-model="formData.price"
          :style="{ width: '480px' }"
          placeholder="请输入价格"
        />
      </el-form-item>
      <el-form-item label="库存" prop="count">
        <el-input
          v-model="formData.count"
          :style="{ width: '480px' }"
          placeholder="请输入库存"
        />
      </el-form-item>
      <el-form-item label="排序" prop="orderby">
        <el-input
          v-model="formData.orderby"
          :style="{ width: '480px' }"
          placeholder="请输入排序"
        />
      </el-form-item>
      <el-form-item label="文档" prop="mdurl">
        <el-upload
          action="upload"
          :before-upload="beforeMdUpload"
          :before-remove="beforeMdRemove"
          multiple
          :auto-upload="true"
          :file-list="mdFileList"
          :limit="1"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
